from ninja.security import HttpBearer

from system.models import Users
from utils.cj_jwt import parse_payload
from utils.cj_ninja import FuFilters
from utils.cj_response import ErrorResponse
from utils.usual import get_user_info_from_token


class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        if token == "supersecret":
            return token
        elif not token:
            return "token不能为空"
        else:
            return TimeoutError(403, "token格式错误")


def check_token(func):
    """
    token认证装饰器
    :param func:
    :return:
    """

    def wrapper(request, *args, **kwargs):
        token = request.META.get("HTTP_AUTHORIZATION")
        if not token:
            return ErrorResponse(code=401, msg="token为空，请先登录")
        token = token.replace('Bearer ', "")
        result = parse_payload(token)
        code = result['code']
        if code != 200:
            return ErrorResponse(code=401, msg=result['msg'])
        # 将token解析的用户ID返回到请求头
        request.userId = result['data']['userId']
        return func(request, *args, **kwargs)

    return wrapper


def data_permission(request, filters: FuFilters):
    user_info = get_user_info_from_token(request)
    # if user_info['is_superuser']:
    #     return filters
    user = Users.objects.get(id=user_info['userId'])
    # data_range_qs = user.role.values_list('data_range', flat=True)
    # dept_ids = user.role.values_list('dept__id', flat=True)

    # 如果有多个角色，取数据权限最大的角色
    # data_range = max(list(data_range_qs))

    # 仅本人数据权限
    # if data_range == 0:
    #     filters.creator_id = user_info['id']

    # 本部门数据权限
    # if data_range == 1:
    #     filters.belong_dept = user_info['dept']

    # 本部门及以下数据权限
    # if data_range == 2:
    #     pass

    # 所有数据权限
    # if data_range == 3:
    #     pass

    # 自定义数据权限
    # if data_range == 4:
    #     filters.belong_dept__in = list(dept_ids)

    return filters
